package com.xyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyy.common.PageResult;
import com.xyy.dto.PushDTO;
import com.xyy.dto.PushQueryDTO;
import com.xyy.entity.Push;
import com.xyy.mapper.PushMapper;
import com.xyy.service.PushService;
import com.xyy.vo.PushVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 推文服务实现类
 */
@Slf4j
@Service
public class PushServiceImpl implements PushService {

    @Autowired
    private PushMapper pushMapper;

    @Override
    @Transactional
    public void createPush(PushDTO pushDTO, Long publisherId) {
        Push push = new Push();
        BeanUtils.copyProperties(pushDTO, push);
        push.setPublisherId(publisherId);
        push.setViewCount(0L);
        push.setLikeCount(0L);
        push.setCommentCount(0L);
        
        pushMapper.insert(push);
        log.info("创建推文成功，ID: {}", push.getId());
    }

    @Override
    @Transactional
    public void updatePush(PushDTO pushDTO, Long publisherId) {
        // 验证推文是否存在
        Push existingPush = pushMapper.selectById(pushDTO.getId());
        if (existingPush == null) {
            throw new RuntimeException("推文不存在");
        }
        
        // 验证权限：超级管理员可以修改所有推文，普通管理员只能修改自己的推文
        // 注意：这里需要传入adminService来检查管理员级别，暂时保持原有逻辑
        if (!existingPush.getPublisherId().equals(publisherId)) {
            throw new RuntimeException("无权限修改此推文");
        }

        Push push = new Push();
        BeanUtils.copyProperties(pushDTO, push);
        push.setPublisherId(publisherId);
        
        pushMapper.updateById(push);
        log.info("更新推文成功，ID: {}", push.getId());
    }

    @Override
    @Transactional
    public void deletePush(Long pushId, Long publisherId) {
        // 验证推文是否存在且属于当前管理员
        Push existingPush = pushMapper.selectById(pushId);
        if (existingPush == null) {
            throw new RuntimeException("推文不存在");
        }
        if (!existingPush.getPublisherId().equals(publisherId)) {
            throw new RuntimeException("无权限删除此推文");
        }

        pushMapper.deleteById(pushId);
        log.info("删除推文成功，ID: {}", pushId);
    }

    @Override
    @Transactional
    public void batchDeletePush(List<Long> pushIds, Long publisherId) {
        // 验证所有推文是否属于当前管理员
        List<Push> pushes = pushMapper.selectBatchIds(pushIds);
        for (Push push : pushes) {
            if (!push.getPublisherId().equals(publisherId)) {
                throw new RuntimeException("无权限删除推文: " + push.getId());
            }
        }

        pushMapper.deleteBatchIds(pushIds);
        log.info("批量删除推文成功，数量: {}", pushIds.size());
    }

    @Override
    @Transactional
    public void publishPush(Long pushId, Long publisherId) {
        // 验证推文是否存在且属于当前管理员
        Push existingPush = pushMapper.selectById(pushId);
        if (existingPush == null) {
            throw new RuntimeException("推文不存在");
        }
        if (!existingPush.getPublisherId().equals(publisherId)) {
            throw new RuntimeException("无权限发布此推文");
        }

        Push push = new Push();
        push.setId(pushId);
        push.setStatus(1); // 已发布
        
        pushMapper.updateById(push);
        log.info("发布推文成功，ID: {}", pushId);
    }

    @Override
    @Transactional
    public void withdrawPush(Long pushId, Long publisherId) {
        // 验证推文是否存在且属于当前管理员
        Push existingPush = pushMapper.selectById(pushId);
        if (existingPush == null) {
            throw new RuntimeException("推文不存在");
        }
        if (!existingPush.getPublisherId().equals(publisherId)) {
            throw new RuntimeException("无权限撤回此推文");
        }

        Push push = new Push();
        push.setId(pushId);
        push.setStatus(2); // 已撤回
        
        pushMapper.updateById(push);
        log.info("撤回推文成功，ID: {}", pushId);
    }

    @Override
    public PageResult<PushVO> pageQuery(PushQueryDTO queryDTO, Integer current, Integer size) {
        Page<PushVO> page = new Page<>(current, size);
        IPage<PushVO> result = pushMapper.selectPushPage(page, queryDTO);
        
        // 设置状态文本
        result.getRecords().forEach(this::setStatusText);
        
        return new PageResult<>(
            result.getRecords(),
            result.getTotal(),
            result.getCurrent(),
            result.getSize()
        );
    }

    @Override
    public PushVO getPushById(Long pushId) {
        PushVO pushVO = pushMapper.selectPushDetailById(pushId);
        if (pushVO != null) {
            setStatusText(pushVO);
        }
        return pushVO;
    }

    @Override
    @Transactional
    public void incrementViewCount(Long pushId) {
        // 先查询当前浏览次数
        Push existingPush = pushMapper.selectById(pushId);
        if (existingPush != null) {
            Push push = new Push();
            push.setId(pushId);
            push.setViewCount(existingPush.getViewCount() + 1); // 增加1次浏览
            
            pushMapper.updateById(push);
        }
    }
    
    /**
     * 设置状态文本
     */
    private void setStatusText(PushVO pushVO) {
        if (pushVO.getStatus() != null) {
            switch (pushVO.getStatus()) {
                case 0:
                    pushVO.setStatusText("草稿");
                    break;
                case 1:
                    pushVO.setStatusText("已发布");
                    break;
                case 2:
                    pushVO.setStatusText("已撤回");
                    break;
                default:
                    pushVO.setStatusText("未知状态");
                    break;
            }
        }
    }
}
